import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinpendingpage.dart';
import 'package:opene/ui/checkin/checkinreceivedpage.dart';
import 'package:toast/toast.dart';

import 'checkinmodel.dart';

class Checkin extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CheckinPage();
  }
}

class CheckinPage extends StatefulWidget {
  @override
  _CheckinPageState createState() => _CheckinPageState();
}

class _CheckinPageState extends BaseState<CheckinPage> {
  bool isasc = false;
  String pending = "pending";
  String received = "received";
  String empty = "empty";
  List<DataDTO> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Transportation Management";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setLayoutBottomContentGone();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        checkinTransportationStatus();
      });
    });
  }

  void _updateRadio(int value) {
    setState(() {
      hint = "";
      this.type = value;
      isasc = false;
      checkinTransportationStatus();
    });
  }

  void didPopNext() {
    setState(() {
      // 这里刷新页面状态
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15),
            child: Text(
              "Transportation Status",
              style: TextStyle(color: MyAppTheme.nearlyBlue, fontSize: 16.0),
            ),
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 1,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        pending,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: this.type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                      ),
                      onTap: () {
                        _updateRadio(1);
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 2,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        received,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: this.type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                      ),
                      onTap: () {
                        _updateRadio(2);
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 3,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        empty,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: this.type == 3 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                      ),
                      onTap: () {
                        _updateRadio(3);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15),
            child: Row(
              children: <Widget>[
                Expanded(
                    flex: 2, //设置权重
                    child: Text(
                      'Transportation',
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    )),
                Visibility(
                  visible: type > 1 ? true : false,
                  child: Expanded(
                      flex: 1, //设置权重
                      child: Text(
                        'Dropped',
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                      )),
                ),
                Visibility(
                  visible: type == 2 ? false : true,
                  child: Expanded(
                    flex: 1, //设置权重
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          isasc = !isasc;
                          data = data.reversed.toList();
                        });
                      },
                      child: Row(
                        children: [
                          Text(
                            type > 1 ? "Empty" : "Expected",
                            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                          ),
                          Image.asset(
                            isasc ? 'assets/images/ic_double_triangle_up.png' : 'assets/images/ic_double_triangle_down.png',
                            width: 15,
                            height: 15,
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        DataDTO searchOther = data[index];
        print("index:${index}");
        return Column(
          children: [
            GestureDetector(
              onTap: () {
                checkinInfo(type, searchOther);
              },
              child: Row(
                children: [
                  Visibility(
                    visible: searchOther.operationMethod != null ? true : false,
                    child: Image.asset(
                      Utils.getStringisEmpty(searchOther.operationMethod).toLowerCase() == "container"
                          ? 'assets/images/ic_calendar.png'
                          : Utils.getStringisEmpty(searchOther.operationMethod).toLowerCase() == "truck"
                              ? 'assets/images/ic_fire_truck.png'
                              : Utils.getStringisEmpty(searchOther.operationMethod).toLowerCase() == "express"
                                  ? 'assets/images/ic_package.png'
                                  : 'assets/images/ic_calendar.png',
                      width: 15,
                      height: 15,
                    ),
                  ),
                  Container(
                    width: 5,
                  ),
                  Expanded(
                    flex: 2, //设置权重
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          Utils.getStringisEmpty(searchOther.number),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        ),
                        Text(
                          Utils.getStringisEmpty(searchOther.uniqId),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        ),
                      ],
                    ),
                  ),
                  Visibility(
                    visible: type == 2 ? false : true,
                    child: Expanded(
                        flex: 1, //设置权重
                        child: Text(
                          type == 1 ? Utils.getStringisEmpty(searchOther.expected) : Utils.getStringisEmpty(searchOther.dropDate),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        )),
                  ),
                  Visibility(
                    visible: type == 1 ? false : true,
                    child: Expanded(
                        flex: 1, //设置权重
                        child: Text(
                          type == 2 ? Utils.getStringisEmpty(searchOther.dropDate) : Utils.getStringisEmpty(searchOther.expected),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        )),
                  ),
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 15,
                  ),
                ],
              ),
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void checkinTransportationStatus() async {
    Map<String, dynamic> map = new HashMap();
    switch (type) {
      case 1:
        map['transportationStatus'] = "pending";
        break;
      case 2:
        map['transportationStatus'] = "received";
        break;
      case 3:
        map['transportationStatus'] = "empty";
        break;
    }

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkinTransportationStatus, params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      CheckinBean checkinBean = CheckinBean.fromJson(baseResponse.data);
      setState(() {
        pending = "pending(${checkinBean.pending})";
        received = "received(${checkinBean.received})";
        empty = "empty(${checkinBean.empty})";
        data.clear();
        if (checkinBean.list != null) {
          data.addAll(checkinBean.list);
        }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void checkinInfo(int type, DataDTO data) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["id"] = data.id;
    map["containerNo"] = data.number;
    map["expected"] = data.expected;
    map["uniqId"] = data.uniqId;
    switch (type) {
      case 1:
        map['transportationStatus'] = "pending";
        break;
      case 2:
        map['transportationStatus'] = "received";
        break;
      case 3:
        map['transportationStatus'] = "empty";
        break;
    }

    // showDialogFunction();
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkinInfo, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      CheckinInfo checkinInfo = CheckinInfo.fromJson(baseResponse.data);
      switch (type) {
        case 1:
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => CheckinPending(data: checkinInfo)),
          ).then((value) => {
                if (value != null && value)
                  {
                    setState(() {
                      checkinTransportationStatus();
                    })
                  }
              });
          break;
        case 2:
        case 3:
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => CheckinReceived(data: checkinInfo,type: type)),
          ).then((value) => {
                if (value != null && value)
                  {
                    setState(() {
                      checkinTransportationStatus();
                    })
                  }
              });
          break;
      }
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    // TODO: implement setNext
  }

  @override
  void setReset() {
    // TODO: implement setReset
  }
}
